package com.core.reach.snowflakeactive.service;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 * @author ga.zhang
 * @version V1.0
 * @description: TODO
 * @date 2020/4/2 11:19
 **/
@Slf4j
@Service
public class IdGeneratorService {

    private long workId = 0;
    private long dataCenterId = 1;
    private Snowflake snowflake = IdUtil.createSnowflake(workId, dataCenterId);

    @PostConstruct
    public void init() {
        try {
            workId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
            log.info("当前机器的workId为:{}", workId);
        } catch (Exception e) {
            log.info("获取当前机器的workId失败：{}", e.getMessage());
            workId = NetUtil.getLocalhostStr().hashCode();
        }
    }

    public synchronized long snowFlakeId(){
        return snowflake.nextId();
    }

    public synchronized long snowFlakeId(long workerId, long dataCenterId){
        Snowflake snowflake = IdUtil.createSnowflake(workId, dataCenterId);
        return snowflake.nextId();
    }

//    public static void main(String[] args) {
//        IdGeneratorService idGeneratorService = new IdGeneratorService();
//        System.out.println(idGeneratorService.snowFlakeId());
//    }

}
